// import { minify } from "terser";
// import walk from "walk";
// import fs from "fs-extra";

const fs = require("fs-extra");
const walk = require("walk");
const { minify } = require("terser");

const walker = walk.walk("./dist");
const terserConfig = {
    sourceMap: false,
    toplevel: true,
    module: true,
    ecma: 2016,
};
const group = new Set();
walker.on("file", function (root, fileStats, next) {
    const abp = root + "/" + fileStats.name;
    group.add(abp);
    next();
});

walker.on("errors", function (root, nodeStatsArray, next) {
    console.warn(root);
    next();
});

walker.on("end", function () {
    console.log("开始压缩", group.size);
    const total = group.size;
    [...group].reduce((col, i, index) => {
        return col.then((res) => {
            process.stdout.write(`${index + 1} / ${total} | ${i}\r`);
            if (i.endsWith(".js"))
                return fs.promises
                    .readFile(i, { encoding: "utf-8" })
                    .then((code) => {
                        if (code)
                            minify(code, terserConfig).then((res) =>
                                fs.outputFile(i, res.code)
                            );
                    })
                    .catch(() => {
                        console.log("Error ", i);
                    });
        });
    }, Promise.resolve());
});
